package cn.glc.daily.life.web.support;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * 使用spring自带的邮件发送
 * {@link org.springframework.mail.javamail.JavaMailSenderImpl}
 *
 * @author simon
 * @date 2021/4/4 22:52
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
@Component
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class MailSupport {

    private final JavaMailSenderImpl mailSender;

    /**
     * // TODO: 2021/4/5 邮件模板设置
     * 邮件发送
     *
     * @param to
     * @return
     */
    public boolean send(String to, String content) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            messageHelper.setFrom("sanfubaby@163.com", "DAILY_LIFE");
            messageHelper.setTo(to);
            messageHelper.setSubject("邮箱验证码");
            messageHelper.setText(content, true);
            mailSender.send(mimeMessage);
            return true;
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("邮件发送失败", e);
            return false;
        }
    }
}
